Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 22/43 Β· 161.3 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Operators

The '+' operator is overloaded: it is used for string concatenation and
arithmetic addition. This may cause problems when inadvertently mixing
strings and numbers. As a unary operator, it can convert a numeric
string to a number.

// Concatenate 2 strings
console.log('He' + 'llo'); // displays Hello
// Add two numbers
console.log(2 + 6); // displays 8
// Adding a number and a string results in concatenation (from left to
right)
console.log(2 + '2'); // displays 22
console.log('$' + 3 + 4); // displays $34, but $7 may have been expected
console.log('$' + (3 + 4)); // displays $7
console.log(3 + 4 + '7'); // displays 77, numbers stay numbers until a
string is added
// Convert a string to a number using the unary plus
console.log(+'2' === 2); // displays true
console.log(+'Hello'); // displays NaN

Similarly, the '*' operator is overloaded: it can convert a string into
a number.

console.log(2 + '6'*1); // displays 8
console.log(3*'7'); // 21
console.log('3'*'7'); // 21
console.log('hello'*'world'); // displays NaN

Arithmetic

JavaScript supports the following binary arithmetic operators:

| + | addition |
|---|---|
| - | subtraction |
| * | multiplication |
| / | division (returns a floating-point valu… |
| % | modulo (returns the remainder) |
| ** | exponentiation |

JavaScript supports the following unary arithmetic operators:

| + | unary conversion of string to number |
|---|---|
| - | unary negation (reverses the sign) |
| ++ | increment (can be prefix or postfix) |
| -- | decrement (can be prefix or postfix) |

let x = 1;
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
console.log(x); // x is 3; displays 3
console.log(x--); // displays 3; x becomes 2
console.log(x); // displays 2; x is 2
console.log(--x); // x becomes 1; displays 1

The modulo operator displays the remainder after division by the
modulus. If negative numbers are involved, the returned value depends on
the operand.

const x = 17;
console.log(x%5); // displays 2
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────